<?php
if(!defined("IN_PHPSCUP"))exit("hacking");
//配置返回资料是否自动加入反斜线当溢出字符，设置为0关闭该功能
error_reporting(7);
@ set_magic_quotes_runtime(0);
$time = explode(" ", microtime());
$time_start = $time[0] + $time[1];
define("SYS_TIME_START", $time_start);
unset ($time_start, $time);
if (function_exists("memory_get_usage") && !defined("SYS_MEMORY_START")) {
	define("SYS_MEMORY_START", memory_get_usage());
}

if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
	define('LF', "\r\n");
} else {
	define('LF', "\n");
}
if(!isset($_SERVER["HTTP_REFERER"]))
{
$_SERVER["HTTP_REFERER"] = '';
}
if(!isset($HTTP_SERVER_VARS["HTTP_REFERER"]))
{
$HTTP_SERVER_VARS["HTTP_REFERER"] = '';
}

$php_self_temp = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
$_SERVER['QUERY_STRING'] && $php_self_temp .= "?".$_SERVER['QUERY_STRING'];
$php_self =$_SERVER['REQUEST_URI']?$_SERVER['REQUEST_URI']:$php_self_temp;
$http_host =$_SERVER['HTTP_HOST']?$_SERVER['HTTP_HOST']:$HTTP_SERVER_VARS['HTTP_HOST'];
$web_url='http://'.$http_host.$php_self;
$from_url=$_SERVER["HTTP_REFERER"]?$_SERVER["HTTP_REFERER"]:$HTTP_SERVER_VARS["HTTP_REFERER"];

define('WEB_URL',$web_url);
define('FROM_URL',$from_url);
unset($GLOBALS);
define('ROLE_Y_ID', 'admin:1|scup:1'); //默认用户组编号,游客组

define('ROLE_P_ID', 'admin:3|scup:3'); //默认用户组编号,普通用户组

define('ROLE_V_ID', 'admin:2|scup:2'); //超级管理员用户组

define('ROLE_CON_FILE', 'admin|scup'); //用户组控制权限的包名

define('VIEW_CHARSET', 'utf-8'); //网页编码

define('IS_DEBUG', '0'); //是否开启网站错误信息显示,0表示否，1表示开启

define('PHPSCUP_VERSION','1.6.0');

define('LANG','zh-cn');
define('COOKIE_DOMAIN','');
define('COOKIE_PATH','');
define('COOKIE_SECURE','0');
define('COOKIE_PREFIX','');
define('SYSTEM_MYSQL_SESSION','1');
define('SESSION_PREFIX','');
define('SESSION_MAX_LIFE_TIME','1440');
define('IS_START_VIEWSTYLE',0);

class SCup {
	var $SCup_view_root = null; //视图层文件路径

	var $SCup_app_root = null; //逻辑层文件路径

	var $SCup_model_root = null; //控制层文件路径

	var $SCup_filter_root = null; //过滤层文件路径   

	var $SCup_compiled_root = null; //编译后文件路径

	var $SCup_caches_root = null; //缓存文件路径   

	var $SCup_app_name = "default"; //默认使用的控制层文件名

	var $SCup_act_name = "index"; //默认执行的动作名

	var $SCup_app = null; //逻辑层实体

	var $SCup_view = null; //视图层实体

	var $SCup_act = null; //执行的动作实体 

	var $SCup_message = null; //提示，错误，警告信息实体

	var $user_power_array_file = null; //用户权限控制文件数组

	var $SCup_DB = null; //连接数据库实体

	var $SCup_user_session = null; //用户session实体

	var $SCup_user_msg = array (); //用户所以信息

	var $SCup_user = null; //用户信息实体   

	var $SCup_user_checking = false; //用户登入验证

	var $SCup_name = 'scup'; //此应用包的名字

	var $SCup_nav = NULL; //网站导航实体

	var $SCup_category = NULL; //网站分类实体
	
	var $SCup_nav_file = NULL;
	
	function __construct($config = array ()) {

		$this->SCup($config);

	}

	function SCup($config) {
		$GLOBALS['SCup'] = & $this;	
		$this->SCup_name = $config['SCup_name'];
		//加载核心基类文件
		if (!empty ($config['core_libs'])) {
			foreach ($config['core_libs'] as $lib) {
				require ($lib);
			}
		}
		//加载其他基础文件
		if (!empty ($config['external_libs'])) {
			foreach ($config['external_libs'] as $lib) {
				require ($lib);
			}
		}
		//连接数据库
		$this->_get_db();

		//验证用户登入情况及得到部分用户信息	
		$this->_init_session();		
		//unset ($GLOBALS['SCup']);

		$lang = new Lang();
		if(!isset($_GET['langid']))
		{
		$_GET['langid']='';
		}
		if(!empty($_GET['langid']))
		{
			      $setlang = $_GET['langid'];
				  if(preg_match("/[.\/]/",$setlang))
		          {
		            $lang->_lang_tp = LANG;
		  
                  } 
				  else
				  {
				  $lang->_lang_tp = $setlang;				  
				  }
		          $lang->_set_lang($lang->_lang_tp);
		}
		$langtype = $lang->_get_cookie_langtype();
		$GLOBALS['langtype'] =$langtype;
		$GLOBALS['langdata'] =$GLOBALS['Lang']->_get_lang_typesdata();		
		if(is_file(ROOT_PATH . '/data/config_'.$langtype.'.inc.php'))
		{
          require(ROOT_PATH . '/data/config_'.$langtype.'.inc.php');
		}
		else
		{
		  require(ROOT_PATH . '/data/config.inc.php');
		}   

		
		if (ENABLED_GZIP) {
			ob_start('ob_gzhandler');
		} else {
			ob_start();
		}		
	
        if(defined("VIEW_TYPE_DEFAULT"))
		{
		$this->SCup_view_root = $config['view_root'] . '/' . VIEW_TYPE_DEFAULT;	
		$this->SCup_compiled_root = $config['compiled_root'] . '/' . VIEW_TYPE_DEFAULT;

		$this->SCup_caches_root = $config['caches_root'] . '/' . VIEW_TYPE_DEFAULT;			

		}else
		{
		      
			  
		      if(!isset($_GET['vt']))
			  {
			    $_GET['vt']='';
			  }
			  if(!$_GET['vt'])
			  {
			    if(get_cookie('vt'))
			    {
			    $_GET['vt']=get_cookie('vt');
			    }			  
			  }
              if(!IS_START_VIEWSTYLE)
			  {
			  $_GET['vt'] = 0;
			  }
			  
		      if(!empty($_GET['vt']))
			  {
			  set_cookie('vt',$_GET['vt'],time()+3600*24); 
		      $this->SCup_view_root = $config['view_root'] . '/' . $_GET['vt'];
		
		      $this->SCup_compiled_root = $config['compiled_root'] . '/' . $_GET['vt'];

		      $this->SCup_caches_root = $config['caches_root'] . '/' . $_GET['vt'];				  
			  }
			  else
			  {
		      $this->SCup_view_root = $config['view_root'] . '/' . VIEW_TYPE;
		
		      $this->SCup_compiled_root = $config['compiled_root'] . '/' . VIEW_TYPE;

		      $this->SCup_caches_root = $config['caches_root'] . '/' . VIEW_TYPE;	
		      }
		
		}
		


		$this->SCup_app_root = $config['app_root'];

		$this->SCup_filter_root = $config['filter_root'];

		$this->SCup_model_root = $config['model_root'];

		$this->SCup_app_name = $config['default_app'] ? $config['default_app'] : 'default';

		$this->SCup_act_name = $config['default_act'] ? $config['default_act'] : 'index';

		$this->user_power_file = $config['user_power_file'];




		//加载系统语言包及该文件的语言包
		$lang->_get_lang('system');
	}

	function Run() {


		//产生视图实体
		$this->_get_view();

		//判断是否关闭系统
		if ((!SYSTEM_OPEN) && ($this->SCup_name != 'admin')) 
		{   
	        $notice = &get_message(array('msg'=>SYSTEM_OPEN_REASON,'url'=>'noskip','title'=>'提示'));
	        $notice ->display();			

		}

		if (SYSTEM_URL_REWRITE) {
			//从新得到get数据，用于静态网页，和伪静态网页
			$this->SCup_view->_re_get_url();
		}

		$this->SCup_app_name = !empty ($_GET['app']) ? trim($_GET['app']) : $this->SCup_app_name;
		$this->SCup_act_name = !empty ($_GET['act']) ? trim($_GET['act']) : $this->SCup_act_name;

		$app = $this->SCup_app_name;
		$act = $this->SCup_act_name;

		//过滤get参数和post参数及cookie参数
		$filter_file = $this->SCup_filter_root . "/{$app}.{$act}.flt.php";
		if (is_file($filter_file)) {
			new Flt();
		} else {
			new Filter();
		}



		//用户权限验证及控制
		$UserPower = new UserPower($this->user_power_array_file, $this->SCup_user_msg);
		$UserPower->Power($app, $act);

		$app_file = $this->SCup_app_root . "/{$app}.app.php";
		if (!is_file($app_file)) {
			exit ('Missing controller');
		}
		
		//产生控制器 
		require ($app_file);		
		$app_class_name = ucfirst($app) . 'App';
		//实例化控制器 
		
		
		$app = new $app_class_name ();

		$app->do_action($act);
		$app->destruct();

		$this->_destruct();
	}

	//产生数据库实体	
	function & _get_db() {
		if ($this->SCup_DB == null) {
			require (ROOT_PATH . '/lib/sql/' . DB_TYPE . '.lib.php');
			$data_class_name = 'SCup_' . DB_TYPE;
			$this->SCup_DB = new $data_class_name ();
			$this->SCup_DB->connect();

		}

		return $this->SCup_DB;

	}

	//提示，错误，警告信息实体	
	function & _get_message($array = array ()) {
		if ($this->SCup_message == null) {
			$this->SCup_message = new MessageBase($array);
		}

		return $this->SCup_message;
	}

	//得到用户信息	
	function _init_session() {
		if ($this->SCup_user_session == null) {
			if (SYSTEM_MYSQL_SESSION) {
				require (ROOT_PATH . '/lib/session/mysession.lib.php');
				$this->SCup_user_session = new SCup_session(get_table_name('sessions'));
			} else {
				require (ROOT_PATH . '/lib/session/session.lib.php');
				$this->SCup_user_session = new SCup_session();
			}

		}

		return $this->SCup_user_msg;
	}

	//得到主导航信息	
	function _get_nav($filename = '', $lang = '') {
		if ($this->SCup_nav == null) {
			require (ROOT_PATH . '/lib/nav.lib.php');
			$this->SCup_nav = new Nav($filename, $lang);
		}

		return $this->SCup_nav;
	}

	//得到用户信息	
	function _get_user() {
		if ($this->SCup_user == null) {
			require (ROOT_PATH . '/lib/passports/' . USER_TYPE . '.php');
			$user_msg_class_name = 'SCup_' . ucfirst(USER_TYPE);
			$this->SCup_user = new $user_msg_class_name ();

		}

		return $this->SCup_user;
	}

	//得到栏目分类信息	
	function _get_category() {
		if ($this->SCup_category == null) {
			require (ROOT_PATH . '/lib/category.lib.php');
			$this->SCup_category = new Category();

		}

		return $this->SCup_category;
	}

	function _get_category_data($type = '') {
		return @include (ROOT_PATH . '/data/category/category_' . $type .'_'.trim($GLOBALS['Lang']->_lang_tp).'.php');
	}

	//产生视图实体	
	function & _get_view() {
		if ($this->SCup_view == null) {
			$this->SCup_view = new scupView();
			$this->_init_view();
		}
		return $this->SCup_view;
	}

	//初始化视图实体
	function _init_view() {
		$this->SCup_view->template_dir = $this->SCup_view_root;
		$this->SCup_view->cache_dir = $this->SCup_caches_root;
		$this->SCup_view->compile_dir = $this->SCup_compiled_root;

		$this->SCup_view->widget_dir = ROOT_PATH . '/' . $this->SCup_name . '/widget';
	}

	function _destruct() {

	}
}

//得到数据库表名
function get_table_name($tablename) {
	return DB_PREFIX . $tablename;
}

//得到某目录下的所有文件夹名及文件名
function get_all_dirname($dirname) {
	$all_dir = array ();
	$lang_dir_handle = opendir($dirname);

	while (($lang_dir = readdir($lang_dir_handle)) !== false) {
		if (!preg_match("/^\./", $lang_dir)) {
			$all_dir[] = $lang_dir;
		}
	}

	closedir($lang_dir_handle);
	return $all_dir;
}

// 得到视图实体
function & get_view() {

	return $GLOBALS['SCup']->_get_view();
}

// 得到数据库连接实体
function & get_db() {
	return $GLOBALS['SCup']->_get_db();
}

// 得到应用包的名字
function get_scup_name() {

	return $GLOBALS['SCup']->SCup_name;
}

//得到提示，错误，警告信息实体
function & get_message($array = array ()) {
	return $GLOBALS['SCup']->_get_message($array);
}

function & get_model() {
      static $_model;

		if (empty($_model)) {
			$model_file = ROOT_PATH . "/scupcore/model.base.php";
			if (!is_file($model_file)) {
				exit ('Missing BaseModel');
			}
			include_once($model_file);
			$_model = new BaseModel();

		}

		return $_model;
}

function scup_define($source)
{
    if (is_string($source))
    {
        /* 导入数组 */
        $source = include($source);
    }
    if (!is_array($source))
    {
        /* 不是数组，无法定义 */
        return false;
    }
    foreach ($source as $key => $value)
    {
        if (is_string($value) || is_numeric($value) || is_bool($value) || is_null($value))
        {
            /* 如果是可被定义的，则定义 */
            define(strtoupper($key), $value);
        }
    }
}


function set_cookie($name,$value='',$time=0,$cookie_path='',$cookie_domain='',$cookie_secure=false) 
{
	if(setcookie(COOKIE_PREFIX.$name,$value,$time,$cookie_path,$cookie_domain,$cookie_secure))
	{
	     return true;
	}
	else
	{
	     return false;
	}
}

function get_cookie($name)
{   
    if(empty($name)||!isset($_COOKIE[COOKIE_PREFIX.$name]))
	{
        return '';	
	}
	else
	{
        return $_COOKIE[COOKIE_PREFIX.$name];	
	}
}

//给cookie赋值
function assign_cookie($name,$value)
{
    $_COOKIE[COOKIE_PREFIX.$name]=$value;
}


//用户组字符串解析
function role_deal($str) {
	$array = array ();
	$str_array = explode('|', $str);
	foreach ($str_array as $key => $value) {
		if ($value) {
			$str_v = explode(':', $value);
			$array[$str_v[0]] = $str_v[1];

		}

	}

	return $array;
}

function sys_debug() {

	if (!defined("SYS_TIME_START")) {
		return false;
	}
	if (!defined("SYS_MEMORY_START") || !function_exists("memory_get_usage")) {
		return false;
	}
	$time = explode(" ", microtime());
	$end_time = $time[0] + $time[1];
	$time_used = round(($end_time -SYS_TIME_START), 5);

	$mysql_count = $GLOBALS['SCup']->_get_db()->querynum;
	$mysql_times = $GLOBALS['SCup']->_get_db()->querytime;

	$end = memory_get_usage();
	$used = $end -SYS_MEMORY_START;
	if ($used <= 1024) {
		$used = "1 KB";
	}
	elseif ($used > 1024 && $used < (1024 * 1024)) {
		$used = round(($used / 1024), 4) . " KB";
	} else {
		$used = round(($used / (1024 * 1024)), 4) . " MB";
	}
	$memory = $used;
	$msg = "Processed in " . $time_used . " second(s), mysql: " . $mysql_count . " queries";
	$msg .= ", " . $mysql_times . " second(s)";
	if ($memory) {
		$msg .= ", memory: " . $memory;
	}

	return $msg;
}

function get_parent_id($cat_id)
{
	$categorydata = & $GLOBALS['SCup']->_get_category_data('prot');
		
	 	//获取parent_id
		$parent_id=0;
		foreach ($categorydata as $key => $value)
		{
			if($value['cat_id']==$cat_id)
			{
				$parent_id=$value['parent_id'];
				break;
			}
		}
	return $parent_id;
}
?>